package red.yancloud.www.ui.dialog;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.appcompat.widget.AppCompatSeekBar;
import androidx.appcompat.widget.AppCompatTextView;
import org.greenrobot.eventbus.EventBus;
import red.yancloud.www.R;
import red.yancloud.www.common.Constants;
import red.yancloud.www.common.MessageEvent;
import red.yancloud.www.db.sharedpreference.ReadSettingShardPreference;
import red.yancloud.www.manager.ThemeManager;
import red.yancloud.www.ui.read.ReadSettingActivity;
import red.yancloud.www.util.ImageUtils;
import red.yancloud.www.util.ScreenUtils;
import red.yancloud.www.util.ToastUtils;

/**
 * @Org：www.shuhai.com(陕西书海网络科技有限公司)
 * @Author：风不会停息 on 2019/7/10 16:30
 * E_Mail：yh131412hys@163.com
 * Describe：阅读更多设置
 * Change：
 * @Version：V1.0
 */
public class BookReadMoreSettingDialog extends Dialog implements OnClickListener,OnSeekBarChangeListener{

	private Context mContext;
	private ReadSettingShardPreference readSetting;
	private AppCompatImageView[] readStyleView;
	private int[] readStyleId;
	private AppCompatImageView[] lineSpaceView;
    private int[] lineSpaceId;
    private AppCompatImageView[] readThemeViews;
    private int[] readThemeIds;
    private int[] readThemes;
	private AppCompatSeekBar lightSeekBar;
	/**
	 * 行间距
	 */
	private float[] lineSpaceSize;
	private int light; // 亮度值
	private AppCompatTextView systemLight;
	private int size = 30; // 字体大小
	private AppCompatTextView textSizePrompt;
	private boolean isCheck = false;
	private static BookReadMoreSettingDialog instance;

	private BookReadMoreSettingDialog(Context context, int themeResId) {
		super(context, themeResId);
		this.mContext = context;
		init();
	}

	private void init() {
		this.setCanceledOnTouchOutside(true);
		this.setCancelable(true);
	}

	private BookReadMoreSettingDialog(Context context) {
		this(context, R.style.dialog_from_bottom);
		this.readSetting = ReadSettingShardPreference.Companion.getInstance();
	}

	public static BookReadMoreSettingDialog getInstance(Context context){
		if(instance == null){
			return new BookReadMoreSettingDialog(context);
		}
		return instance;
	}

	public void showView(){
		show();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dialog_read_more_setting);
		initValues();
		initView();
	}

	private void initValues() {
		Window window = getWindow();
		WindowManager.LayoutParams lp = window.getAttributes();
		DisplayMetrics dms = mContext.getResources().getDisplayMetrics();
		lp.width = dms.widthPixels;
		lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
		lp.gravity = Gravity.BOTTOM;
		window.setAttributes(lp);
	}

	private void initView() {

        //字号
		findViewById(R.id.read_size_decrease).setOnClickListener(this);
		findViewById(R.id.read_size_add).setOnClickListener(this);
        textSizePrompt = (AppCompatTextView) findViewById(R.id.text_size);
        size = readSetting.getTextSize();
        textSizePrompt.setText(String.valueOf(size));

        //初始换行间距
        lineSpaceId = new int[] {R.id.line_spacing_big,R.id.line_spacing_among,R.id.line_spacing_small};
        lineSpaceView = new AppCompatImageView[lineSpaceId.length];
        for (int i = 0; i < lineSpaceId.length; i++) {
            lineSpaceView[i] = (AppCompatImageView) findViewById(lineSpaceId[i]);
            lineSpaceView[i].setOnClickListener(new LineSpaceOnClickListener());
        }
        lineSpaceSize = new float[]{2.5f,1.8f,1.3f};
        for (int i = 0; i < lineSpaceSize.length; i++) {
            if(lineSpaceSize[i] == readSetting.getLineSpace()){
                lineSpaceView[i].setSelected(true);
                setLineSpace(lineSpaceSize[i]);
            }
        }

	    systemLight = (AppCompatTextView) findViewById(R.id.system_light);
	    systemLight.setOnClickListener(this);
	    if(readSetting.getSystemLight()){
	    	isCheck = false;
	    	systemLight.setSelected(true);
	    }else{
	    	systemLight.setSelected(false);
	    	isCheck = true;
	    }

		findViewById(R.id.screen_switch).setOnClickListener(this);
		findViewById(R.id.set_more).setOnClickListener(this);

        //初始化主题模式、日间夜间护眼等模式
		readStyleId = new int[] {R.id.read_style_day_text,
				R.id.read_style_blue_text, R.id.read_style_eye_text,
				R.id.read_style_parchment_text};
		readStyleView = new AppCompatImageView[readStyleId.length];

		for (int i = 0; i < readStyleId.length; i++) {
			readStyleView[i] = (AppCompatImageView) findViewById(readStyleId[i]);
			readStyleView[i].setOnClickListener(new ReadStyleOnClickListener());
		}

		readThemes = new int[]{ThemeManager.READ_STYLE_THEME_00,ThemeManager.READ_STYLE_THEME_01,ThemeManager.READ_STYLE_THEME_02,ThemeManager.READ_STYLE_THEME_03};

		for (int i = 0; i < readStyleId.length; i++) {
			if(readSetting.getReadStyle() == i){
				readStyleView[i].setSelected(true);
			}
		}

        findViewById(R.id.theme_more).setOnClickListener(this);

		//初始换屏幕亮度
		lightSeekBar = (AppCompatSeekBar) findViewById(R.id.light_seekbar);
		lightSeekBar.setOnSeekBarChangeListener(this);
		lightSeekBar.setProgress(readSetting.getLight());
	}

	/**
	 * 主题设置按钮点击监听事件
	 * @author Wangxu
	 *
	 */
	private class ReadStyleOnClickListener implements View.OnClickListener {

		@Override
		public void onClick(View v) {
			for (int i = 0; i < readStyleView.length; i++) {
				if (v == readStyleView[i]) {
					readStyleView[i].setSelected(true);
//					readSetting.setReadStyle(i);
					readSetting.setReadStyle(readThemes[i]);
				} else {
					readStyleView[i].setSelected(false);
				}
			}

			/**
			 * 设置阅读主题样式
			 */
			EventBus.getDefault().post(new MessageEvent(Constants.ReadStatus.READ_STYLE_THEME,readSetting.getReadStyle()));
		}
	}

	/**
	 * 设置主题样式字体颜色背景图片等元素
	 * @param attrId
	 * @param color
	 */
	private void setReadStyle(int attrId,int color){
		Bitmap bitmap = BitmapFactory.decodeResource(mContext.getResources(),attrId);
		if (null != bitmap) {
			bitmap = ImageUtils.zoomBitmap(bitmap, ScreenUtils.getScreenWidth(), ScreenUtils.getScreenHeight());
//			pageFactory.setBgBitmap(bitmap);
		}
	}

	/**
	 * 行间距按钮点击监听事件
	 * @author Wangxu
	 *
	 */
	private class LineSpaceOnClickListener implements View.OnClickListener {

		@Override
		public void onClick(View v) {
			for (int i = 0; i < lineSpaceId.length; i++) {
				if(v == lineSpaceView[i]){
					lineSpaceView[i].setSelected(true);
					setLineSpace(lineSpaceSize[i]);
					EventBus.getDefault().post(new MessageEvent(Constants.ReadStatus.READ_LINESPACE,lineSpaceSize[i]));
				}else{
					lineSpaceView[i].setSelected(false);
				}
			}
		}
	}

	/**
	 * 设置行间距
	 * @param size
	 */
	private void setLineSpace(float size){
		readSetting.setLineSpace(size);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
            case R.id.read_size_decrease:
                setFontSize(false);
                break;
            case R.id.read_size_add:
                setFontSize(true);
                break;
            case R.id.theme_more:
                new BookReadThemeSettingDialog(mContext).show();
                dismiss();
                break;
            case R.id.system_light:
                Message message = new Message();
                message.what = Constants.ReadStatus.LIGHT_SYSTEM;
                if(readSetting.getSystemLight()){
                    systemLight.setSelected(false);
                    message.arg1 = Constants.ReadStatus.LIGHT_SYSTEM_CLOSE;
					EventBus.getDefault().post(new MessageEvent(Constants.ReadStatus.LIGHT_SYSTEM,Constants.ReadStatus.LIGHT_SYSTEM_CLOSE));
				}else{
                    systemLight.setSelected(true);
                    message.arg1 = Constants.ReadStatus.LIGHT_SYSTEM_OPEN;
                    lightSeekBar.setProgress(readSetting.getLight());
					EventBus.getDefault().post(new MessageEvent(Constants.ReadStatus.LIGHT_SYSTEM,Constants.ReadStatus.LIGHT_SYSTEM_OPEN));
				}
                readSetting.setSystemLight(!readSetting.getSystemLight());
                break;
			case R.id.screen_switch:
				dismiss();
				break;
			case R.id.set_more:
				((Activity)mContext).startActivityForResult(new Intent(mContext, ReadSettingActivity.class), Constants.REQUEST_CODE.READ_SETTING);
				dismiss();
				break;
		}
	}

	/**
	 * 设置字体大小
	 * @param isAdd
	 */
	private void setFontSize(boolean isAdd) {
		if(isAdd){
			if (size > mContext.getResources().getDimension(R.dimen.chapter_font_max_size)) {
				ToastUtils.showToast( mContext.getResources().getString(R.string.max_imun));
				return;
			}
			size += 2;
		}else{
			if (size < mContext.getResources().getDimension(R.dimen.chapter_font_mix_size)) {
                ToastUtils.showToast(mContext.getResources().getString(R.string.mix_imun));
				return;
			}
			size -= 2;
		}
		readSetting.setTextSize(size);
		textSizePrompt.setText(readSetting.getTextSize() + "");
		EventBus.getDefault().post(new MessageEvent(Constants.ReadStatus.READ_FONT_SIZE,size));
	}

	/**
	 * 屏幕亮度手动调试监听
	 */
	@Override
	public void onProgressChanged(SeekBar seekBar, int progress,
			boolean fromUser) {
		if(isCheck){
			light = seekBar.getProgress();
			readSetting.setLight(light);
			EventBus.getDefault().post(new MessageEvent(Constants.ReadStatus.LIGHT_LEVEL,light));
		}
	}

	@Override
	public void onStartTrackingTouch(SeekBar seekBar) {
		systemLight.setSelected(false);
		readSetting.setSystemLight(false);
		isCheck = !isCheck;
	}

	@Override
	public void onStopTrackingTouch(SeekBar seekBar) {

	}
}
